/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.secure.aop;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.MoonConstants;
import org.moon.framework.autoconfigure.cache.CacheService;
import org.moon.framework.autoconfigure.secure.AuthUtils;
import org.moon.framework.autoconfigure.secure.domain.AuthInfo;
import org.moon.framework.autoconfigure.springmvc.response.R;
import org.moon.framework.autoconfigure.utils.Func;
import org.moon.framework.autoconfigure.utils.IpUtils;
import org.moon.framework.autoconfigure.utils.JsonUtils;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * token拦截器校验
 * @author ninglong
 */
@Slf4j
@AllArgsConstructor
public class SecureInterceptor implements HandlerInterceptor {
	
	private CacheService cacheService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		String requestFrom = request.getHeader(MoonConstants.REQUEST_FROM);
		// feign调用不需要验证
		if(Func.isNotEmpty(requestFrom) && MoonConstants.RequestFormEnum.feign.name().equals(requestFrom)){
			return true;
		}
		String token = AuthUtils.getToken();
		if(Func.isEmpty(token)){
			return secureTokenFailMsg(request, response);
		}
		AuthInfo info = AuthUtils.getAuthInfo();

		if(Func.isEmpty(info)){
			return secureTokenFailMsg(request, response);
		}
		//TODO 暂时不考虑单体工程
//		boolean refresh = LocalDateTime.now().minusSeconds(MoonConstants.SESSION_TIME_OUT+MoonConstants.REFRESH_SESSION).isAfter(info.getOptTime());
//		if(refresh){
//			AuthUtils.setAuthInfo(info);
//		}
		return true;
	}
	
	private boolean secureTokenFailMsg(HttpServletRequest request, HttpServletResponse response){
		log.warn("{}认证失败，请求接口：{}，请求IP：{}，请求参数：{}", MoonConstants.HEADER_ACCESS_TOKEN,request.getRequestURI(), IpUtils.getIpAddr(request), JsonUtils.obj2string(request.getParameterMap()));
		R<Void> result = R.fail(MoonConstants.AUTHENTICATION);
		response.setHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE);
		response.setCharacterEncoding("utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		try {
			response.getWriter().write(Objects.requireNonNull(JsonUtils.obj2string(result)));
		} catch (IOException ex) {
			log.error(ex.getMessage());
		}
		return false;
	}
}